import { createVNode, Directive, DirectiveBinding, render } from 'vue'
import ContextmenuComponent from '../components/ContextmenuComponent.vue'
type containerType = HTMLElement | null
const CTX_CONTEXTMENU_HANDLER = 'CTX_CONTEXTMENU_HANDLER'
const contextmenuListener = (
  el: HTMLElement,
  event: MouseEvent,
  binding: DirectiveBinding
) => {
  console.log(el, 'el')
  
  event.stopPropagation()
  event.preventDefault()
  const menus = binding.value
  console.log(menus, 'menu')
  if (!menus) return
  const removeContextmenu = () => {
    if (container) {
      document.body.removeChild(container)
      container = null
    }
    el.classList.remove('contextmenu-active')
    document.body.removeEventListener('scroll', removeContextmenu)
    window.removeEventListener('resize', removeContextmenu)
  }
  let container: containerType = null
  const options = {
    axis: {x: event.x, y: event.y}, // 注意这里是关键，一定要把x和y的值赋值成event里面的x和y
    el,
    menus,
    removeContextmenu
  }
  container = document.createElement('div')
  //   生成虚拟dom
  const vm = createVNode(ContextmenuComponent, options, null)
  
  //   挂载到container容器上，
  render(vm, container)
  document.body.appendChild(container)
  console.log(vm, 'vm')
  //   el.classList.add('contextmenu-active')
  window.addEventListener('scroll', removeContextmenu) // 只要屏幕里面有滑动事件和窗口大小改变时发生的事件的话，就取消context菜单
  window.addEventListener('resize', removeContextmenu)
  
}
const ContextmenuDirective: Directive = {
  mounted(el: HTMLElement, binding) {
    el.addEventListener('contextmenu', (event: MouseEvent) =>
      contextmenuListener(el, event, binding)
    )
  },
  unmounted(el: HTMLElement, binding) {
    el.removeEventListener('contextmenu', (event: MouseEvent) =>
      contextmenuListener(el, event, binding)
    )
  },
}
export default ContextmenuDirective
